package org.example.chapter1;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.example.model.Weather;
import rx.Single;
import rx.SingleSubscriber;

import java.io.IOException;

public class Demo1_3_3 {
    private static OkHttpClient httpClient;
    static{
        httpClient = new OkHttpClient();
    }
    public static void main(String[] args) {
        Single.create(new Single.OnSubscribe<String>(){

            @Override
            public void call(SingleSubscriber<? super String> singleSubscriber) {
                if (!singleSubscriber.isUnsubscribed()) {
                    String url = "https://www.mxnzp.com/api/weather/current/深圳市?app_id=mqhjpnelpmkbqvr9&app_secret=VXhucERRNlplUlFkWW9vVzZnV3NoZz09";
                    Request request = new Request.Builder()
                            .url(url)
                            .build();
                    httpClient.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            if (response.isSuccessful()) {
                                if (response.body() != null) {
                                    String responseBody = response.body().string();
                                    singleSubscriber.onSuccess(responseBody);
                                }

                            }
                        }
                    });
                }
            }
        }).subscribe(new SingleSubscriber<String>() {
            @Override
            public void onSuccess(String s) {
                JSONObject jsonObject = JSONObject.parseObject(s);
                Weather weather = jsonObject.getObject("data", Weather.class);
                System.err.println(JSONObject.toJSONString(weather,true));
            }

            @Override
            public void onError(Throwable throwable) {
                System.err.println(throwable.getMessage());
            }
        });
    }

    private void test(){
        Single.create(new Single.OnSubscribe<Integer>(){

            @Override
            public void call(SingleSubscriber<? super Integer> singleSubscriber) {
                if (!singleSubscriber.isUnsubscribed()) {
                    singleSubscriber.onSuccess(1);
                }
            }
        }).subscribe(new SingleSubscriber<Integer>() {
            @Override
            public void onSuccess(Integer integer) {
                System.err.println("integer=" + integer);
            }

            @Override
            public void onError(Throwable throwable) {
                System.err.println(throwable.getMessage());
            }
        });
    }
}
